package com.Tcp.Dome;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Tcpdome {
	public static List<Socket> socketList = new ArrayList<Socket>();

	public static void main(String[] args) {
		try {
			ServerSocket server = new ServerSocket(8080);
			System.out.println("服务器已准备");
			while (true) {
				Socket socket = server.accept();
				if (socket != null) {
					socketList.add(socket);
					new Thread(new SocketTread(socket)).start();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

class SocketTread implements Runnable {
	private Socket socket;

	public SocketTread(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		String msg = null;
		try {
			System.out.println("已连接" + socket.getInetAddress().getHostName() + "客户端");
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			while ((msg = in.readLine()) != null) {
				if (msg.trim().equals("EXIT")) {
					Tcpdome.socketList.remove(socket);
				} else {
					System.out.println(msg);
					dispatch(msg);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void dispatch(String msg) {
		for (Socket socket : Tcpdome.socketList) {
			try {
				PrintWriter out = new PrintWriter(socket.getOutputStream());
				out.println(socket.getInetAddress().getHostName() + " : " + msg);
				out.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}
}